package cn.qu.phizline.webserver;

import cn.qu.phizline.event.init.InitEvent;
import cn.qu.phizline.event.login.LoginEvent;
import cn.qu.phizline.webserver.api.v1.converter.Apiv1MessageConverter;
import cn.qu.phizline.webserver.event.handle.init.InitHandle;
import cn.qu.phizline.webserver.event.handle.login.LoginHandle;
import cn.qu.phizline.webserver.ws.WebServer;
import cn.qu.phizline.webserver.ws.WebServerHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@EnableCaching
@EnableWebSocket
@SpringBootApplication
@EnableAutoConfiguration
public class F2fServerApplication extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
    @Autowired
    private ApplicationContext applicationContext;

    @Bean(name = "apiv1MessageConverter")
    public HttpMessageConverters apiv1MessageConverter(WebServer webServer) {
        HttpMessageConverter<?> apiv1MessageConverter = new Apiv1MessageConverter(webServer);
        return new HttpMessageConverters(apiv1MessageConverter);
    }

    @Bean
    public WebServer webServer() {
        WebServer webServer = new WebServer();
        webServer.register(LoginEvent.class, LoginHandle.class);
        webServer.register(InitEvent.class, InitHandle.class);
        return webServer;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        WebServerHandle webServerHandle = new WebServerHandle();
        applicationContext.getAutowireCapableBeanFactory().autowireBean(webServerHandle);

        registry.addHandler(webServerHandle, "/ws").setAllowedOrigins("*");
    }


    public static void main(String[] args) {
        SpringApplication.run(F2fServerApplication.class, args);
    }

}
